<?php
namespace App\Common;

use App\Book;
use App\User;

/**
 * Created by PhpStorm.
 * User: ye
 * Date: 2017/12/3
 * Time: 下午11:15
 */

class BookSearch {

    private $userinfo;

    public function __construct($userinfo) {
        $this->userinfo = $userinfo;
    }

    public function search($input = []) {
        $show_other = array_get($input, 'other', 0);
        $next_cursor = array_get($input, 'next_cursor', 1);
        $perpage = array_get($input, 'perpage', 10);

        if ($show_other == 0) {
            $booksBuilder = Book::whereHas('pivot', function ($query) {
                    $query->where('user_id', $this->userinfo->id);
                });
        } else {
            $booksBuilder = Book::whereHas('pivot', function ($query) {
                $query->where('user_id', '<>', $this->userinfo->id);
            });
        }

        $books = $booksBuilder->with('pivot')
            ->skip(($next_cursor -1)* $perpage)
            ->take($perpage)
            ->get();

        return $books;
    }

}